package cn.northsea.controller;


import cn.northsea.common.Result;
import cn.northsea.entity.PrivateChatMessage;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@CrossOrigin
@RestController
@RequestMapping("/common")
public class CommonController {

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private SerializeUtil serializeUtil;


    /**
     * 获取聊天消息历史记录
     *
     * @param fromUser 发送方
     * @param toUser 接收方
     */
    @GetMapping("/getHistoryMessage")
    public Result<List<PrivateChatMessage>> getHistoryMessage(@RequestParam("fromUser") String fromUser,
                                                              @RequestParam("toUser") String toUser) throws IOException {
        //构建返回结果
        List<PrivateChatMessage> messageResult = new ArrayList<PrivateChatMessage>();

        //获取当前fromUser与toUser的聊天记录
        String fromMessages = redisTemplate.opsForValue().get(fromUser);
        // 判断redis中是否有当前fromUser的聊天记录
        if (!StringUtils.isEmpty(fromMessages)){
            // 反序列化为List对象
            List<PrivateChatMessage> fromMessagesList = serializeUtil.deserializeList(fromMessages);
            // 遍历,将privateChatMessage.toUser等于toUser的PrivateChatMessage对象添加到messageResult中
            for (PrivateChatMessage privateChatMessage : fromMessagesList) {
                if (privateChatMessage.getToUser().equals(toUser)){
                    messageResult.add(privateChatMessage);
                }
            }
        }
        // 判断redis中是否有当前toUser的聊天记录
        String toMessages = redisTemplate.opsForValue().get(toUser);
        if (!StringUtils.isEmpty(toMessages)){
            // 反序列化为List对象
            List<PrivateChatMessage> toMessagesList = serializeUtil.deserializeList(toMessages);
            // 遍历,将privateChatMessage.toUser等于fromUser的PrivateChatMessage对象添加到messageResult中
            for (PrivateChatMessage privateChatMessage : toMessagesList) {
                if (privateChatMessage.getToUser().equals(fromUser)){
                    messageResult.add(privateChatMessage);
                }
            }
        }

        // 将messageResult结果集,按照时间字段排序(从小到大)
        messageResult.sort((o1, o2) -> o1.getTimestamp().compareTo(o2.getTimestamp()));
        // 返回messageResult结果集
        return Result.success(messageResult);
    }

//    /**
//     * 获取未读消息数量
//     *
//     */
//    @GetMapping("/getUnreadMessageCount")


}
